package com.mairuide._frame.base;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mairuide.datalog.DataOperationImportLog;
import com.mairuide.inspectionReport.Report;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mairuide._frame.utils.Config;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.platgroupuser.PlatGroupUser;
import com.mairuide.platgroupuser.PlatGroupUserService;
import com.mairuide.platmanager.PlatManager;
import com.mairuide.platmanager.PlatManagerService;
import com.mairuide.platroleuser.PlatRoleUserService;

public class BaseController {
	
	private static Logger log = LoggerFactory.getLogger(BaseController.class);
	
	private String AJAX_HEADER = "X-Requested-With";
	
	@Resource
	protected HttpServletRequest request;
	
	@Resource
	protected HttpServletResponse response;
	
	@Resource
	protected Config config;
	
	@Resource
	private PlatRoleUserService platRoleUserService;
	
	@Resource
	private PlatGroupUserService platGroupUserService;
	
	@Resource
	private PlatManagerService platManagerService;
	
	/**
	 * 获取当前登录人
	 * @return
	 */
	protected PlatManager getLoginUser() {
		PlatManager lu = (PlatManager) request.getSession().getAttribute("loginUser");
		return lu;
	}
	
	/**
	 * 区分登录人是代理商，还是运营中心部门的人员，还是总部及下级部门 的人员
	 * @return 1:代理商角色,2:运营中心部门,3:总部或总部下级部门
	 */
	protected int diffLoginUser() {
		PlatManager loginUser = this.getLoginUser();
		
		// 判断登录人是不是总部或总部下级部门， 若是 返回result = 3 
		boolean beglongHeadQuarters = platGroupUserService.checkBelongHeadQuartersByUserId(loginUser.getId());
		if (beglongHeadQuarters) {
			return 3;
		}
		
		throw new RuntimeException(String.format("人员ID %s 既不是代理商，也不属于运营中心部门，也不属于总部", loginUser.getId()));
	}
	
	/**
	 * 自已的部门ID或上级的部门ID
	 * @return
	 */
	protected Integer superiorGroupId() {
		PlatManager loginUser = this.getLoginUser();
		// 上级(非子账号代理商用自己，子账号代理商用上级)
		PlatManager superior = null;
		if (loginUser.getIsSubAccount() != null && loginUser.getIsSubAccount().intValue() == 1) {
			// 子账号， 找上级
			superior = platManagerService.findOne(loginUser.getSuperiorId());
		} else {
			// 上级，不变
			superior = loginUser;
		}
		Integer superiorId = superior.getId();
		List<PlatGroupUser> platGroupUserList = platGroupUserService.findByUserId(superiorId);
		if(platGroupUserList == null || platGroupUserList.isEmpty()) {
			throw new RuntimeException(String.format("ID=%d的人员没有门", superiorId));
		}
		Integer groupId = platGroupUserList.get(0).getGroupId();
		if(groupId == null) {
			throw new RuntimeException("部门没有ID");
		}
		return groupId;
	}
	
	@ExceptionHandler(value = Exception.class)
	public String handleException(Exception e) throws ServletException, IOException{
		e.printStackTrace();
		log.error("error message =["+e.getMessage()+"]");
		String ajaxHeader = request.getHeader(AJAX_HEADER);
		if(StringUtils.isEmpty(ajaxHeader)){
			return "/error";
		}else{
			response.getWriter().write(new Gson().toJson(ERROR("服务异常")));
			response.getWriter().flush();
		}
		return null;
	}
	
	public Object SUCCESS(Object data){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("result", "success");
		result.put("data", data);
		return result;
	}
	
	public Object SUCCESS(){
		return SUCCESS(null);
	}
	
	public Object ERROR(String desc){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("result", "fail");
		result.put("data", desc);
		return result;
	}
	
	/**
	 * 文件上传
	 * @param files
	 * @return
	 * @throws IOException
	 */
	protected JsonArray persistFile(MultipartFile file) throws IOException {
		JsonArray array = new JsonArray();
		if(file != null && file.getSize() > 0) {
			String fileName = file.getOriginalFilename();
			File dir = new File(config.getUploadFilePath());
			dir.mkdirs();
			final File f = new File(config.getUploadFilePath(), StringUtils.generateUUID()+fileName);
			f.createNewFile();
			file.transferTo(f);
			JsonObject object = new JsonObject();
			object.addProperty("fileName", fileName);
			object.addProperty("fileUrl", f.getPath());
			array.add(object);
		}
		return array;
	}
	/**
	 * 案件报告文件上传
	 * @param file
	 * @return
	 * @throws IOException
	 */
	protected DataOperationImportLog reportFile(MultipartFile file) throws IOException {
		DataOperationImportLog dil = new DataOperationImportLog();
		if(file != null && file.getSize() > 0) {
			String fileName = file.getOriginalFilename();
			File dir = new File(config.getUploadFilePath()+"/report");
			dir.mkdirs();
			final File f = new File(config.getUploadFilePath()+"/report", fileName);
			f.createNewFile();
			file.transferTo(f);
			dil.setFileName(fileName);
			dil.setFilePath(f.getPath());
			dil.setFileSize(String.valueOf(file.getSize()));
		}
		return dil;
	}
	
}
